from flask import Flask,request,jsonify
from flask_sqlalchemy import SQLAlchemy
import json
from config import Config
from flask_cors import CORS

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
CORS(app)

class Order(db.Model):
    __tablename__ = 'orders'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(50),default='')
    price = db.Column(db.Float,default=0)

# db.drop_all()
# db.create_all()

@app.route('/add',methods=['POST',"GET"])
def insert():
    if request.method == 'POST':
        name = request.data
        print(name)
        gain = json.loads(name)
        res = Order(name=gain['name'],price=float(gain['price']))
        db.session.add(res)
        db.session.commit()
        return "OK"
    elif request.method == 'GET':
        gain = Order.query.all()
        list1 = []
        for i in gain:
            dict1 = {}
            dict1['id'] = i.id
            dict1['name'] = i.name
            dict1['price'] = i.price
            list1.append(dict1)
        print(list1)
        return jsonify({'code':200,"matter":list1})
    else:
        pass
        
@app.route('/del',methods=['DELETE'])
def dels():
    id = request.args.get('id')
    Order.query.filter_by(id=id).delete()
    db.session.commit()
    return jsonify({'code':200})

if __name__ == '__main__':
    app.run()
    